package com.heima.search.listen;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.constants.ArticleConstants;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

@Component
@Slf4j
public class SyncArticleListener {
    @Autowired
    RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void receiveMessage(String msg){

        if (Optional.ofNullable(msg).isPresent()){
            log.info("接收到消息:{}",msg);
            Map map= JSON.parseObject(msg,Map.class);
            //构造请求
            IndexRequest request=new IndexRequest("app_info_article");
            request.id(map.get("id").toString());
            request.source(msg, XContentType.JSON);

            //发送请求并返回结果
            try {
                client.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("存储失败:{}",e.toString().substring(0,300));
            }
            log.info("储存到es成功");
        }
    }
}